package com.thank.web.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.thank.dto.User;
import com.thank.exception.UserNotExistException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * description: none
 *
 * @author thank
 * 2018/2/19 0:43
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @PostMapping
    @JsonView(User.UserSimpleView.class)
    public User create(@Valid @RequestBody User user, BindingResult errors) {

        if (errors.hasErrors()) {
            errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
        }

        System.out.println(user.toString());
        user.setId("1");
        return user;
    }


    @PutMapping("/{id:\\d+}")
    @JsonView(User.UserSimpleView.class)
    public User update(@Valid @RequestBody User user, BindingResult errors) {

        if (errors.hasErrors()) {
            errors.getAllErrors().stream().forEach(error -> {
                FieldError fieldError = (FieldError) error;
                String message = fieldError.getField() + ": " + fieldError.getDefaultMessage();
                System.out.println(message);
            });
        }
        System.out.println(user.toString());
        user.setId("1");
        return user;
    }


    @RequestMapping(method = RequestMethod.GET)
    @JsonView(User.UserSimpleView.class)
    public List<User> query(@RequestParam(value = "username") String username) {
        List<User> userList = new ArrayList<>();
        userList.add(new User());
        userList.add(new User());
        userList.add(new User());
        System.out.println(username);
        return userList;
    }

    @RequestMapping(value = "/{id:\\d+}", method = RequestMethod.GET)
    @JsonView(User.UserDetailView.class)
    public User get(@PathVariable String id) {

//        throw new UserNotExistException(id);
        System.out.println("进入get服务" + id);
        User user = new User();
        user.setUsername("thank");
        return user;
    }


    @DeleteMapping(value = "/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public void delete(@PathVariable String id) {
        System.out.println(id);
    }
}
